<?php
if (! defined ( 'BASEPATH' ))
    exit ( 'No direct script access allowed' );

class AkunHistory extends Controller {
    public function __construct() {
        parent::__construct ();
        $this->_data = array ();
        $this->load->model ( 'akunhistory_model' );
        isController('akuntansi','akunHistory');
    }
    protected function _view($template, $data = array(), $result = false) {
        if ($data && is_array ( $data )) {
            return $this->load->view ( $template, $data, $result );
        }
        return $this->load->view ( $template, $this->_data, $result );
    }
    public function index() {
        redirect ( 'akuntansi/akunHistory/view' );
    }
    protected function _executeView() {
        $array = $this->uri->uri_to_assoc ( 3, array ('id', 'action' ) );
        // delete action
        if (isAccess('akuntansi','akunhistory','delete') && $array ['action'] == 'delete' && $array ['id']) {
            if ($this->akunhistory_model->delete($array['id'])) {
                $this->_data['errorMessage'] =  'Berhasil Delete History Akun' ;
                $this->_data['isSuccess'] =  true ;
            } else {
                $this->_data['errorMessage'] =  'Gagal Delete History Akun' ;
            }
        }
    }
    public function view() {
    	if (! isAccess ( 'akuntansi', 'akunhistory', 'view'))
            redirect (); 
        $array = $this->uri->uri_to_assoc ( 3, array ('id', 'year', 'month', 'tipe', 'action', 'page' ) );
        $this->_executeView ();
        $array['page'] = (int) $array['page'];

        //List Akun Tipe
        $this->load->model('akuntipe_model');
        $listTipe = $this->config->item('listAkunTipe');
        
        $listAkunTipe = array();
        if($listTipe) foreach($listTipe as $tipe) {
        	$listAkun[$tipe] = $this->akuntipe_model->getList (100, 0, array('akunTipe'=>$tipe));

        	if($listAkun[$tipe]) foreach($listAkun[$tipe] as $k=>$v) {
        		$listAkunTipe[$tipe][$v['akunTipeId']] = $v['akunTipeNama'];
        	}
        }
        $this->_data['listAkunTipe'] = $listAkunTipe;
        
        //Uri
        $array['tipe'] = !empty($array['tipe']) ? $array['tipe'] : 'all';
        $array['year'] = !empty($array['year']) ? $array['year'] : 'all';
        $array['month'] = !empty($array['month']) ? $array['month'] : 'all';
        
        //Where
        $where = array();
        if( !empty($array['year']) && $array['year'] != 'all' )
        	$where['historyPeriodeTahun'] = $array['year'];
        if( !empty($array['month']) && $array['month'] != 'all' )
        	$where['historyPeriodeBulan'] = $array['month'];	
        if( !empty($array['tipe']) && $array['tipe'] != 'all' )
        	$where['akunTipeId'] = $array['tipe'];
     	
        $total = 0;
        if( $array['year'] != 'all' && $array['month'] != 'all' )	
        	$total = $this->akunhistory_model->getCount($where);
        	
        if (($array['page'] + 1) > $total)
            $array['page'] = 0;
            
        $this->load->library('pagination');    
        $limit = $this->config->item('klinik_limit');
        $config = $this->config->item('paging');
        $config['base_url'] = site_url('akuntansi/akunHistory/view/year/'.$array['year'].'/month/'.$array['month'].'/tipe/'.$array['tipe'].'/page/');
        $config['uri_segment'] = 10;
        $config['total_rows'] = $total;
        $config['per_page'] = $limit;
        
        $this->pagination->initialize($config);
        $this->_data['paging'] =  $this->pagination->create_links();
        
        $dataView = array();
        if( $array['year'] != 'all' && $array['month'] != 'all' )
        	$dataView = $this->akunhistory_model->getList($limit, $array['page'], $where);
        
        $this->_data['dataView'] = $dataView;

        $this->_data['uri_to_assoc'] = $array;
        $this->_view ( 'akuntansi/akunHistoryView' );
    }

    protected function _executeEdit() {
        $array = $this->uri->uri_to_assoc ( 3, array ('id', 'year', 'month', 'tipe', 'action' ) );
        
        if ($this->input->post ( 'submit' ) == 'Simpan' && $this->input->post ( 'kirim' ) == 'kirim') {
            $historySaldo = trim ( $this->input->post ( 'historySaldo' ) );
            $historySaldo = str_replace(',', '', $historySaldo);
			
            $data = array ();
            $data ['historySaldo'] = $historySaldo;

            $errors = array ();
            if (!isset ( $historySaldo ))
                $errors [] = 'Input Nilai Saldo';

            if ($errors) {
                $this->_data['errorMessage'] =  implode ( '<br />', $errors ) ;
            } elseif( $this->akunhistory_model->update ( $array['id'], $data ) ) {
                $this->_data['errorMessage'] =  'Berhasil Edit History Akun' ;
                unset($_POST);
                $this->_data['isSuccess'] =  true ;
                
                $akunHistory = $this->akunhistory_model->get ( $array['id'] );
                $this->_data['dataEdit'] = $akunHistory;    
            } else {
                $this->_data['errorMessage'] =  'Gagal Edit History Akun' ;
            }        
        }    
    }

    public function edit() {
    	if (! isAccess ( 'akuntansi', 'akunHistory', 'edit'))
            redirect (); 
        $array = $this->uri->uri_to_assoc ( 3, array ('id', 'year', 'month', 'tipe' ) );
        if ( !$array ['id'] || !$array ['year'] || !$array ['month'] || !$array ['tipe'] )
            show_404 ();
            
        $dataHistory = $this->akunhistory_model->get ( $array ['id'] );
        $this->_data['dataEdit'] = $dataHistory;    
        if (! $dataHistory)
            show_404 ();
        
        $this->_executeEdit();
        $this->_data['uri_to_assoc'] = $array;
        $this->_view ( 'akuntansi/akunHistoryEdit' );
    }
    
	public function exportPdf() {
    	if (! isAccess ( 'akuntansi', 'akunrincian', 'exportexcel'))
            redirect (); 
        $array = $this->uri->uri_to_assoc ( 3, array ('year', 'month') );
		if( !$array['year'] && !$array['month'] )
        	show_404();
        	
        //Data General
        $this->load->helper('inflector');
		$this->load->model('akuntipe_model');
        
		//Set Value
        $dataView = array();
        
        //Get Akun
        $listAkunTipe = $this->config->item('listAkunTipe');
	    if($listAkunTipe) foreach($listAkunTipe as $akun) {
	    
	    	//Get Tipe Akun
	    	$whr[$akun] = array();
	    	$whr[$akun]['akunTipe'] = $akun;
	    	$dataAkun[$akun] = $this->akuntipe_model->getList(100, 0, $whr[$akun]);
	    	
	    	$dataView[$akun] = array();
	    	if($dataAkun[$akun]) foreach($dataAkun[$akun] as $tipe) {
	    		$akunTipeId = get_data($tipe,'akunTipeId');
	    		$akunTipeNama = get_data($tipe,'akunTipeNama');
	    		 
	    		//Get Rincian Akun
	    		$whr2[$akunTipeId] = array();
	    		$whr2[$akunTipeId]['akunTipeId'] = $akunTipeId;
	    		$whr2[$akunTipeId]['historyPeriodeTahun'] = $array['year'];
				$whr2[$akunTipeId]['historyPeriodeBulan'] = $array['month'];
				$dataRincian[$akunTipeId] = $this->akunhistory_model->getList(100, 0, $whr2[$akunTipeId]);
	    		
	    		//Set Data
	    		if($dataRincian[$akunTipeId]) foreach($dataRincian[$akunTipeId] as $key=>$row) {
	    			
	    			$dataView[$akun][$akunTipeNama][$key]['akunKode'] = $row['akunKode'];
	    			$dataView[$akun][$akunTipeNama][$key]['akunNama'] = $row['akunNama'];
	    			$dataView[$akun][$akunTipeNama][$key]['akunSaldo'] = $row['historySaldo'];
	    		}
	    		
	    	}
	    	
	    }

        //Template PDF
        $content = '<page backtop="14mm" backbottom="14mm" pagegroup="new">
				    <page_header>
					<table style="width:100%;">
					    <tr>
							<td style="width:70%;">'.$this->lang->line('global_title').'</td>
							<td style="width:30%;">Laporan Aktiva & Pasiva</td>
					    </tr>
				        <tr>
							<td>'.$this->lang->line('global_title_cab').'</td>
							<td>Periode : '.monthName($array['month']).' '.$array['year'].'</td>
					    </tr>
					    <tr>
							<td>'.$this->lang->line('global_alamat_cab').'</td>
							<td></td>
					    </tr>
					</table>
				    </page_header>
				    <page_footer>
					<table style="width: 100%;">
					    <tr>
						<td style="text-align: right">
						    Page : [[page_cu]]/[[page_nb]]
						</td>
					    </tr>
					</table>
				    </page_footer>
				</page><br /><br /><br />';
	
	    $content .= '<table style="width:100%;">
				     <tbody style="text-align:center;">';

	    $no=1;
	    //Tipe Akun
	    if($dataView) foreach ($dataView as $tipe=>$dataAkun) {
	    	
	    	//Nama Akun
	    	$total[$tipe] = 0;
	    	if($dataAkun) foreach ($dataAkun as $akun=>$dataRincian) {			
	    		$content .= '<tr>
								<td style="width:5%"></td>
								<td style="width:15%"></td>
								<td style="width:35%;text-align:left;"><b>'.$akun.'</b></td>
								<td style="width:5%"></td>
								<td style="width:20%"></td>
							 </tr>';
	    		
			    	//Rincian Akun
			    	if($dataRincian) foreach ($dataRincian as $row) {			
			    		$content .= '<tr>
										<td>'.$no.'</td>
										<td align="left">'.get_data($row,'akunKode').'</td>
										<td align="left">'.get_data($row,'akunNama').'</td>
										<td>Rp. </td>
										<td align="right">'.number_format(get_data($row,'akunSaldo')).'</td>
									 </tr>';
			    		
			    		$total[$tipe] += get_data($row,'akunSaldo');
						$no++;
			    	}
			    	
			    	//Space
			    	$content .= '<tr>
									<td></td>
									<td></td>
									<td align="left">&nbsp;</td>
									<td></td>
									<td></td>
								 </tr>';
	    	}
	    	
	    	if($total[$tipe] > 0) {
	    		//Space 
		    	$content .= '<tr>
								<td></td>
								<td></td>
								<td align="left">&nbsp;</td>
								<td></td>
								<td></td>
							 </tr>';
		    	
		    	//Total
		    	$content .= '<tr>
								<td></td>
								<td></td>
								<td align="left"><b>Total '.$tipe.'</b></td>
								<td><b>Rp.</b></td>
								<td align="right"><b>'.number_format($total[$tipe]).'</b></td>
							 </tr>';
		    	
		    	//Space
		    	$content .= '<tr>
								<td></td>
								<td></td>
								<td align="left">&nbsp;</td>
								<td></td>
								<td></td>
							 </tr>';
	    	}
	    	
	    }
	   
	    $content .= '</tbody>
	                 </table>';
	    
		//Convert to PDF
	    $this->load->library('html2pdf/html2pdf');
	    $html2pdf = new HTML2PDF('L', 'A4');
	    $html2pdf->pdf->SetDisplayMode('fullpage');
	    $html2pdf->writeHTML($content, FALSE);
	    $html2pdf->Output( 'Laporan_Aktiva_Pasiva_'.monthName($array['month']).'_'.$array['year'].'.pdf' );
    }
}